package com.android.love.ui;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.android.app.sdk.AliPay;
import com.alipay.android.msp.Keys;
import com.alipay.android.msp.Result;
import com.alipay.android.msp.Rsa;
import com.android.love.R;
import com.android.love.adapter.MyOrderAdapter;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.LogUtil;
import com.android.love.vo.MyRequest;
import com.android.love.vo.Order;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.unionpay.UPPayAssistEx;

public class MyOrderActivity extends BasePageActivity {

    private List<Order> myorder_list=Collections.emptyList();

    private ViewFinder myorderFinder;

    private ListView myOrderList;

    private PullToRefreshListView mPullToRefreshListView;

    private View footView;

    private int page=1;

    /** 是否弹出加载中提示 **/
    private boolean show=true;

    private MyOrderAdapter myOrderAdapter;

    private int position;

    private static final int RQF_PAY=1;

    private static final int RQF_LOGIN=2;

    private Order order;

    private static final int PLUGIN_VALID=0;

    private static final int PLUGIN_NOT_INSTALLED=-1;

    private static final int PLUGIN_NEED_UPGRADE=2;

    /*****************************************************************
     * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
     *****************************************************************/
    private String mMode="01";

    // private static final String TN_URL_01 = "http://222.66.233.198:8080/sim/gettn";

    Handler mHandler=new Handler() {

        public void handleMessage(android.os.Message msg) {
            Result result=new Result((String)msg.obj);

            switch(msg.what) {
                case RQF_PAY:
                case RQF_LOGIN: {
                    // Toast.makeText(MyOrderDetail_1.this, result.getResult(),
                    // Toast.LENGTH_SHORT).show();
                    result.parseResult();
                    String statusCode=result.getResultStatus();

                    // sResultStatus.put("9000", "操作成功");
                    // sResultStatus.put("4000", "系统异常");
                    // sResultStatus.put("4001", "数据格式不正确");
                    // sResultStatus.put("4003", "该用户绑定的支付宝账户被冻结或不允许支付");
                    // sResultStatus.put("4004", "该用户已解除绑定");
                    // sResultStatus.put("4005", "绑定失败或没有绑定");
                    // sResultStatus.put("4006", "订单支付失败");
                    // sResultStatus.put("4010", "重新绑定账户");
                    // sResultStatus.put("6000", "支付服务正在进行升级操作");
                    // sResultStatus.put("6001", "用户中途取消支付操作");
                    // sResultStatus.put("7001", "网页支付失败");
                    if("9000".equals(statusCode)) {
                        // 支付成功
                        MyRequest modifyReq=new MyRequest();
                        modifyReq.authority=UriHelper.REALM_NAME;
                        modifyReq.path=UriHelper.URL_ORDER_MODIFY;
                        modifyReq.paramers=generateParams(0, 0, 2, order);
                        getDataFromTask(context, ORDER_MODIFY, modifyReq, order.getStatus(), true, false);
                        // ActivityUtil.show(MyOrderDetail_1.this, "支付成功");
                        // Intent intent = new Intent(context, MyOrderActivity.class);
                        // startActivity(intent);
                        // finish();
                    } else if("8000".equals(statusCode)) {
                        // 支付处理中
                        ActivityUtil.show(MyOrderActivity.this, "支付处理中");
                        // Intent intent = new Intent(context, MyOrderActivity.class);
                        // startActivity(intent);
                        // finish();
                    } else {
                        // 支付失败
                        Toast.makeText(MyOrderActivity.this, result.getResult(), Toast.LENGTH_SHORT).show();
                    }
                    // if (statusCode == "4000") {
                    // // 支付成功
                    // }
                    // if (statusCode == "4006") {
                    // // 支付成功
                    // }
                    // if (statusCode == "6001") {
                    // // 支付成功
                    // }

                }
                    break;
                default:
                    break;
            }
        };
    };

    private Handler handler=new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch(msg.what) {
                case ORDER_LIST:
                    position=msg.arg1;
                    Intent intent=new Intent(context, MyOrderDetail_1.class);
                    intent.putExtra("order", myorder_list.get(position));
                    startActivityForResult(intent, 0);
                    break;
                case ZHIFU:
                    // 在线支付或确定收货
                    position=msg.arg1;
                    order=myorder_list.get(position);
                    if(order.getStatus() == 1) {
                        // 在线支付
                        if(order.getChannel() == 1) {
                            // 支付宝
                            try {
                                Log.i("ExternalPartner", "onItemClick");
                                String info=getNewOrderInfo();
                                String sign=Rsa.sign(info, Keys.PRIVATE);
                                sign=URLEncoder.encode(sign);
                                info+="&sign=\"" + sign + "\"&" + getSignType();
                                Log.i("ExternalPartner", "start pay");
                                // start the pay.
                                Log.i(TAG, "info = " + info);

                                final String orderInfo=info;
                                new Thread() {

                                    public void run() {
                                        AliPay alipay=new AliPay(MyOrderActivity.this, mHandler);

                                        // 设置为沙箱模式，不设置默认为线上环境
                                        // alipay.setSandBox(true);

                                        String result=alipay.pay(orderInfo);

                                        Log.i(TAG, "result = " + result);
                                        Message msg=new Message();
                                        msg.what=RQF_PAY;
                                        msg.obj=result;
                                        mHandler.sendMessage(msg);
                                    }
                                }.start();

                            } catch(Exception ex) {
                                ex.printStackTrace();
                                Toast.makeText(MyOrderActivity.this, R.string.remote_call_failed, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // 银联

                            /*************************************************
                             * 
                             * 步骤2：通过银联工具类启动支付插件
                             * 
                             ************************************************/
                            // mMode参数解释：
                            // 0 - 启动银联正式环境
                            // 1 - 连接银联测试环境
                            int ret=UPPayAssistEx.startPay(MyOrderActivity.this, null, null, order.getTrade_no() + "", mMode);
                            if(ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
                                // 需要重新安装控件
                                Log.e(TAG, " plugin not found or need upgrade!!!");

                                AlertDialog.Builder builder=new AlertDialog.Builder(MyOrderActivity.this);
                                builder.setTitle("提示");
                                builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

                                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        // 安装Asset中提供的UPPayPlugin.apk
                                        // 此处可根据实际情况,添加相应的处理逻辑
                                        UPPayAssistEx.installUPPayPlugin(MyOrderActivity.this);
                                    }
                                });

                                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                builder.create().show();

                            }
                            Log.e(TAG, "" + ret);
                        }

                    }
                    if(order.getStatus() == 3) {
                        // 确认收货
                        MyRequest modifyReq=new MyRequest();
                        modifyReq.authority=UriHelper.REALM_NAME;
                        modifyReq.path=UriHelper.URL_ORDER_MODIFY;
                        modifyReq.paramers=generateParams(0, 0, 4, order);
                        getDataFromTask(context, ORDER_MODIFY, modifyReq, order.getStatus(), true, false);
                    }
                    break;

                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View myorderView=inflater.inflate(R.layout.activity_my_order, null);
        setContentView(myorderView);
        myorderFinder=new ViewFinder(myorderView);
        process();
        setListener();
        getData();
    }

    @Override
    protected Boolean loadBottomTab() {
        return false;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void process() {
        super.process();
        myorder_list=new ArrayList<Order>();
        mPullToRefreshListView=myorderFinder.find(R.id.lv_myorder);
        myOrderList=mPullToRefreshListView.getRefreshableView();
        hide(myorderFinder.find(R.id.iv_shuaxin));
        myorderFinder.setText(R.id.top_title, "我的订单");
        footView=LayoutInflater.from(context).inflate(R.layout.loading_item, null);
        TextView textView=(TextView)footView.findViewById(R.id.tv_loading);
        textView.setText("正在加载.....");
        myOrderList.setDividerHeight(10);
        myOrderList.addFooterView(footView);
        hide(footView);
    }

    @Override
    protected void getData() {
        super.getData();
        MyRequest req=new MyRequest();
        req.authority=UriHelper.REALM_NAME;
        req.path=UriHelper.URL_ORDER_LIST;
        req.paramers=generateParams(page);
        getDataFromTask(context, ORDER_LIST, req, myorder_list, show, true);
    }

    @Override
    protected void setListener() {
        super.setListener();
        myorderFinder.find(R.id.iv_shuaxin).setOnClickListener(this);
        myorderFinder.find(R.id.iv_top_meinv).setOnClickListener(this);
        mPullToRefreshListView.setMode(Mode.DISABLED);
        mPullToRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
                LogUtil.i(TAG, "OnLastItemVisibleListener....");
                if(footView != null)
                    footView.setVisibility(View.VISIBLE);
                show=false;
                page++;
                getData();
            }
        });
    }

    /**
     * 得到传递的参数
     * 
     * @return
     * @throws JSONException
     * @throws IOException
     */
    public Map<String, String> generateParams(int page) {
        JSONObject json=new JSONObject();
        TreeMap<String, String> params=new TreeMap<String, String>();
        params.put("app_key", "android");
        params.put("v", "1.0");
        params.put("page", page + "");
        params.put("count", "10");
        if(sp.getValue(USER_ID, 0) != 0)
            params.put("user_id", sp.getValue(USER_ID, 0) + "");
        if(!"".equals(sp.getValue(SIG, "")))
            params.put("sig", sp.getValue(SIG, ""));
        return params;
    }

    /**
     * 得到传递的参数
     * 
     * @return
     * @throws JSONException
     * @throws IOException
     */
    public Map<String, String> generateParams(int page, long goods_id, int status, Order order) {
        JSONObject json=new JSONObject();
        TreeMap<String, String> params=new TreeMap<String, String>();
        params.put("app_key", "android");
        params.put("v", "1.0");
        if(page == -1) {
            params.put("goods_id", goods_id + "");
        } else {
            if(status == -1) {
                params.put("page", page + "");
                params.put("count", "10");
            } else {
                params.put("order_id", order.getOrder_id() + "");
                params.put("status", status + "");
            }
            if(sp.getValue(USER_ID, 0) != 0)
                params.put("user_id", sp.getValue(USER_ID, 0) + "");
            if(!"".equals(sp.getValue(SIG, "")))
                params.put("sig", sp.getValue(SIG, ""));
        }
        return params;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch(v.getId()) {
            case R.id.iv_shuaxin:

                break;
            case R.id.iv_top_meinv:
                finish(true);
                break;

            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        if(arg0 == 0) {
            if(arg2 != null) {
                boolean cancel=arg2.getBooleanExtra("cancel", false);
                boolean wancheng=arg2.getBooleanExtra("wancheng", false);
                boolean zhifu=arg2.getBooleanExtra("zhifu", false);
                if(cancel) {
                    myorder_list.get(position).setStatus(5);
                    myOrderAdapter.notifyDataSetChanged();
                    int order_num=sp.getValue(ORDER_NUM, 0);
                    sp.setValue(ORDER_NUM, --order_num);
                    updateBottomOrder();
                }
                if(wancheng) {
                    myorder_list.get(position).setStatus(4);
                    myOrderAdapter.notifyDataSetChanged();
                }
                if(zhifu) {
                    myorder_list.get(position).setStatus(2);
                    myOrderAdapter.notifyDataSetChanged();
                    int order_num=sp.getValue(ORDER_NUM, 0);
                    sp.setValue(ORDER_NUM, --order_num);
                    updateBottomOrder();
                }
            }
        }

        /*************************************************
         * 
         * 步骤3：处理银联手机支付控件返回的支付结果
         * 
         ************************************************/
        if(arg2 == null) {
            return;
        }

        String msg="";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
        String str=arg2.getExtras().getString("pay_result");
        if(str != null) {
        	
        	if (str.equalsIgnoreCase("success")) {
    			msg = "支付成功！";
    			ActivityUtil.show(MyOrderActivity.this, msg);
    			MyRequest modifyReq=new MyRequest();
                modifyReq.authority=UriHelper.REALM_NAME;
                modifyReq.path=UriHelper.URL_ORDER_MODIFY;
                modifyReq.paramers=generateParams(0, 0, 2, order);
                getDataFromTask(context, ORDER_MODIFY, modifyReq, order.getStatus(), true, false);
    		} else if (str.equalsIgnoreCase("fail")) {
    			msg = "支付失败！";
    			ActivityUtil.show(MyOrderActivity.this, msg);
    		} else if (str.equalsIgnoreCase("cancel")) {
    			msg = "用户取消了支付";
    			ActivityUtil.show(MyOrderActivity.this, msg);
    		}

        	
//            if(str.equalsIgnoreCase("success")) {
//                msg="支付成功！";
//            } else if(str.equalsIgnoreCase("fail")) {
//                msg="支付失败！";
//            } else if(str.equalsIgnoreCase("cancel")) {
//                msg="用户取消了支付";
//            }
//
//            AlertDialog.Builder builder=new AlertDialog.Builder(this);
//            builder.setTitle("支付结果通知");
//            builder.setMessage(msg);
//            builder.setInverseBackgroundForced(true);
//            // builder.setCustomTitle();
//            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
//
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                }
//            });
//            builder.create().show();
        }
    }

    @Override
    public void handle(int tag, Object object) {
        super.handle(tag, object);
        hide(footView);
        switch(tag) {
            case ORDER_LIST:
                if(object != null) {
                    List<Order> orders=(List<Order>)object;
                    if(orders.size() > 0) {
                        LogUtil.i(TAG, "orders----");
                        myorder_list.addAll(orders);
                        if(myOrderAdapter == null) {
                            myOrderAdapter=new MyOrderAdapter(context, loader, myorder_list, handler);
                            myOrderList.setAdapter(myOrderAdapter);
                        } else {
                            myOrderAdapter.notifyDataSetChanged();
                        }
                    }
                }else{
                	page--;
                }
                mPullToRefreshListView.onRefreshComplete();
                break;
            case ORDER_MODIFY:
                if(object != null) {
                    int status=(Integer)object;
                    if(status > 0) {
                        if(status == 4) {
                            // 完成订单
                            ActivityUtil.show(MyOrderActivity.this, "订单已完成");
                            myorder_list.get(position).setStatus(4);
                            myOrderAdapter.notifyDataSetChanged();

                        } else if(status == 2) {
                            // 订单已支付待发货
                            ActivityUtil.show(MyOrderActivity.this, "订单已支付，请等待发货");
                            myorder_list.get(position).setStatus(2);
                            myOrderAdapter.notifyDataSetChanged();
                            int order_num=sp.getValue(ORDER_NUM, 0);
                            sp.setValue(ORDER_NUM, --order_num);
                            updateBottomOrder();
                        }
                        // changeStyle(order);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            finish(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 支付宝订单信息
     * 
     * @return
     */
    private String getNewOrderInfo() {
        StringBuilder sb=new StringBuilder();
        sb.append("partner=\"");
        sb.append(Keys.DEFAULT_PARTNER);
        sb.append("\"&out_trade_no=\"");
        sb.append(order.getOrder_id());
        sb.append("\"&subject=\"");
        if(order.getGoods().size() == 1)
            sb.append(order.getGoods().get(0).getGoods_name());
        else
            sb.append(order.getGoods().get(0).getGoods_name() + "等" + order.getGoods().size() + "件商品");
        sb.append("\"&body=\"");
        if(order.getGoods().size() == 1)
            sb.append(order.getGoods().get(0).getAttribute());
        else
            sb.append(order.getGoods().size() + "件商品");
        sb.append("\"&total_fee=\"");
        sb.append(order.getSum());
        sb.append("\"&notify_url=\"");

        // 网址需要做URL编码
        sb.append(URLEncoder.encode(UriHelper.REALM_NAME+UriHelper.ONLINEPAY));
        sb.append("\"&service=\"mobile.securitypay.pay");
        sb.append("\"&_input_charset=\"UTF-8");
        sb.append("\"&return_url=\"");
        sb.append(URLEncoder.encode("http://m.alipay.com"));
        sb.append("\"&payment_type=\"1");
        sb.append("\"&seller_id=\"");
        sb.append(Keys.DEFAULT_SELLER);

        // 如果show_url值为空，可不传
        // sb.append("\"&show_url=\"");
        sb.append("\"&it_b_pay=\"1m");
        sb.append("\"");

        return new String(sb);
    }

    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    // @Override
    // protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // /*************************************************
    // *
    // * 步骤3：处理银联手机支付控件返回的支付结果
    // *
    // ************************************************/
    // if (data == null) {
    // return;
    // }
    //
    // String msg = "";
    // /*
    // * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
    // */
    // String str = data.getExtras().getString("pay_result");
    // if (str.equalsIgnoreCase("success")) {
    // msg = "支付成功！";
    // } else if (str.equalsIgnoreCase("fail")) {
    // msg = "支付失败！";
    // } else if (str.equalsIgnoreCase("cancel")) {
    // msg = "用户取消了支付";
    // }
    //
    // AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // builder.setTitle("支付结果通知");
    // builder.setMessage(msg);
    // builder.setInverseBackgroundForced(true);
    // // builder.setCustomTitle();
    // builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // dialog.dismiss();
    // }
    // });
    // builder.create().show();
    // }
}
